<script setup>
import * as Cesium from "cesium";
import { onMounted, ref } from "vue";
import ToggleControl from "@/components/ToggleControl.vue";
import LegendControl from "@/components/LegendControl.vue";
import MyPrimitive from "@/primitives/MyPrimitive.js";
import PyramidPrimitive from "@/primitives/PyramidPrimitive.js";
import CirclePrimitive from "@/primitives/CirclePrimitive.js";
import MagicCirclePrimitive from "@/primitives/MagicCirclePrimitive.js";
import FlagPrimitive from "@/primitives/FlagPrimitive";
import WaterPrimitive from "@/primitives/WaterPrimitive.js";
import addEntity from "@/utils/addEntity";
import add3DTiles from "@/utils/add3DTiles";
import addWater from "@/utils/addWater.js";
import addRadar from "@/utils/addRadar.js";

let viewer, baseLayer, enumLayer;
const tianditutkArr = [
  "590447cdbdf97775b57588a69ebb903d",
  "75f1cc913e8d68f7bd4b6f6383f78ceb",
  "4c4c0f03b0bdb58811f657fec0c09eb5",
];
// ['590447cdbdf97775b57588a69ebb903d', '75f1cc913e8d68f7bd4b6f6383f78ceb', '4c4c0f03b0bdb58811f657fec0c09eb5']
const tianditutk =
  tianditutkArr[Math.floor(Math.random() * tianditutkArr.length)];
Cesium.Ion.defaultAccessToken =
  "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJhZjE5ZTBhZC00YzE1LTQyMWYtOWM4MC00NmFlZjZhOGI3ZDciLCJpZCI6MTI4NTI2LCJpYXQiOjE2OTg4MzczOTN9.26EHXec7Ufty_B4e5_YWcB0t--zlquly7r66WVSS9wE";
// 设置Cesium默认视角
Cesium.Camera.DEFAULT_VIEW_RECTANGLE = Cesium.Rectangle.fromDegrees(
  108.4,
  21.3,
  129.3,
  48.6
);
// 是否打开遮罩
const isMask = ref(false);
// 是否打开功能列表
const isToggle = ref(false);
let bgMask;
// 添加摄像头遮罩效果
const addMask = (viewer) => {
  if (!isMask.value) {
    const fs = `
    uniform sampler2D colorTexture;
    uniform sampler2D maskTexture;
    in vec2 v_textureCoordinates;
    void main() {
      vec4 color = texture(colorTexture, v_textureCoordinates);
      float mask = texture(maskTexture, v_textureCoordinates).a;
      out_FragColor = vec4(color.rgb * (1.0 - mask) * 1.3, 1.0);
    }`;
    // 巧用postProcessStage后处理实现自定义渲染效果
    bgMask = viewer.scene.postProcessStages.add(
      new Cesium.PostProcessStage({
        fragmentShader: fs,
        uniforms: {
          maskTexture: "mask.png",
        },
      })
    );
    isMask.value = true;
  }
};
// 移除摄像头遮罩效果
const removeMask = (viewer) => {
  if (isMask.value) {
    viewer.scene.postProcessStages.remove(bgMask);
    isMask.value = false;
  }
  bgMask = undefined;
};
// 添加图层遮罩效果
const addMaskEntity = (viewer) => {
  let mask = new Cesium.Entity({
    polygon: {
      hierarchy: {
        //添加外部区域为1/4半圆，设置为180会报错
        positions: Cesium.Cartesian3.fromDegreesArray([
          0, 0, 0, 90, 179, 90, 179, 0,
        ]),
        //中心挖空的“洞”
        holes: [
          {
            positions: Cesium.Cartesian3.fromDegreesArray([
              118.4, 31.3, 118.4, 38.6, 129.3, 38.6, 129.3, 31.3,
            ]),
            // holes: []
          },
        ],
      },
      material: new Cesium.ColorMaterialProperty(
        Cesium.Color.GRAY.withAlpha(0.6)
      ),
    },
  });
  viewer.entities.add(mask);
};
// 添加地球点击事件
const addClickEvent = (viewer) => {
  let windowPosition;
  // 开启深度测试，控制视角不转到地下
  viewer.scene.globe.depthTestAgainstTerrain = true;
  const canvas = viewer.scene.canvas;
  const mouseHandler = new Cesium.ScreenSpaceEventHandler(canvas);
  // 绑定鼠标左点击事件
  mouseHandler.setInputAction((e) => {
    console.log(e);
    windowPosition = e.position; // 屏幕坐标
    // 屏幕坐标转笛卡尔坐标
    const ray = viewer.camera.getPickRay(windowPosition);
    // 适用于拾取有地形高度的点的坐标，需要开启深度检测
    const catesian = viewer.scene.globe.pick(ray, viewer.scene);
    // 笛卡尔坐标转经纬度坐标
    const lat = Cesium.Math.toDegrees(
      Cesium.Cartographic.fromCartesian(catesian).latitude
    );
    const lng = Cesium.Math.toDegrees(
      Cesium.Cartographic.fromCartesian(catesian).longitude
    );
    console.log("当前经度坐标是:" + lng + ";纬度坐标是:" + lat);
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
};
// 添加实体点击事件
const addEntityClickEvent = (viewer) => {
  const yellowEdge = Cesium.PostProcessStageLibrary.createSilhouetteStage();
  yellowEdge.enabled = false;
  yellowEdge.selected = []
  viewer.scene.postProcessStages.add(yellowEdge);
  const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
  handler.setInputAction((e) => {
    const pickedObject = viewer.scene.pick(e.position);
    console.log('pickedObject', pickedObject);
    viewer.selectedEntity = undefined
    if (Cesium.defined(pickedObject)) {
      viewer.selectedEntity = new Cesium.Entity({
        name: "拾取结果",
        description: pickedObject.description
      })
      yellowEdge.enabled = true;
      yellowEdge.uniforms.thickness = 5
      yellowEdge.uniforms.color = Cesium.Color.YELLOW;
      yellowEdge.selected = [pickedObject.primitive]
    } else {
      yellowEdge.enabled = false;
      yellowEdge.selected = []
    }
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
}
async function addBuilding() {
  const tileset = await Cesium.Cesium3DTileset.fromUrl(
    "https://service-api.onemap.sh.cegn.cn/proxy/service/3dtiles-SHwhitebox/tileset.json?jcmp-token=72b7a04e62ad496db9a63cb3353c08b1"
  )
  console.log("tileset", tileset)
  // 1，添加tileset
  viewer.scene.primitives.add(tileset)
  // 视图定位
  viewer.zoomTo(tileset, new Cesium.HeadingPitchRange(
    0.0, -0.5, tileset.boundingSphere.radius * 2.0
  ))
}
onMounted(async() => {
  baseLayer = new Cesium.ImageryLayer(
    new Cesium.WebMapTileServiceImageryProvider({
      url:
        "http://t0.tianditu.com/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=" +
        tianditutk,
      layer: "tdtImgLayer",
      style: "default",
      format: "image/jpeg",
      tileMatrixSetID: "GoogleMapsCompatible", //使用谷歌的瓦片切片方式
      show: true,
    })
  );
  viewer = new Cesium.Viewer("cesiumContainer", {
    animation: false, // 动画小组件
    baseLayerPicker: false, // 底图组件，选择三维数字地球的底图
    fullscreenButton: false, // 全屏组件
    vrButton: false, // VR模式
    geocoder: false, // 地理编码搜索组件
    homeButton: false, // 首页，点击之后将视图跳转到默认视角
    infoBox: false, // 信息框
    sceneModePicker: false, // 场景模式，切换2D、3D和Columbus Views（CV）模式
    selectionIndicator: false, // 是否显示选取指示器组件
    timeline: false, // 时间轴
    navigationHelpButton: false, // 帮助提示，如何操作数字地球
    navigationInstructionsInitiallyVisible: false,
    // terrain: new Cesium.Terrain.fromWorldTerrain({
    //   url: Cesium.IonResource.fromAssetId(3956),
    //   requestWaterMask: true,    // 请求水体效果所需要的海水波浪数据
    //   requestVertexNormals: true   // 请求地形照明数据
    // }),
    baseLayer,
    contextOptions: {
      requestWebgl2: true, // 开启webgl2渲染
    },
  });

  enumLayer = new Cesium.ImageryLayer(
    new Cesium.WebMapTileServiceImageryProvider({
      url:
        "http://t0.tianditu.com/cia_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cia&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=" +
        tianditutk,
      layer: "tdtCiaLayer",
      style: "default",
      format: "image/jpeg",
      tileMatrixSetID: "GoogleMapsCompatible", //使用谷歌的瓦片切片方式
      show: true,
    })
  );
  // viewer.imageryLayers.add(enumLayer);
  window.baseLayer = baseLayer;
  window.viewer = viewer;
  window.enumLayer = enumLayer;
  // addMask(viewer)
  // addMaskEntity(viewer)
  console.log(new Cesium.PerInstanceColorAppearance());
  // viewer.scene.primitives.add(new MyPrimitive())
  // viewer.scene.primitives.add(new PyramidPrimitive())
  // const circle = new CirclePrimitive()
  // viewer.scene.primitives.add(circle)
  // setTimeout(() => {
  //   console.log("circle", circle)
  // }, 1000);
  const tileset = await Cesium.Cesium3DTileset.fromUrl(
    "https://service-api.onemap.sh.cegn.cn/proxy/service/3dtiles-SHwhitebox/tileset.json?jcmp-token=72b7a04e62ad496db9a63cb3353c08b1"
  )
  console.log("tileset", tileset)
  // 1，添加tileset
  viewer.scene.primitives.add(tileset)
  // 视图定位
  viewer.zoomTo(tileset, new Cesium.HeadingPitchRange(
    0.0, -0.5, tileset.boundingSphere.radius * 2.0
  ))
  // viewer.scene.primitives.add(new MagicCirclePrimitive())
  // viewer.scene.primitives.add(new FlagPrimitive())
  // viewer.scene.primitives.add(new WaterPrimitive());
  // viewer.trackedEntity = viewer.entities.add({
  //   name: "Yellow box outline",
  //   position: Cesium.Cartesian3.fromDegrees(
  //     124.21936679679918,
  //     45.85136872098397,
  //     80.0
  //   ),
  //   box: {
  //     dimensions: new Cesium.Cartesian3(5, 5, 5),
  //     fill: false,
  //     outline: true,
  //     outlineColor: Cesium.Color.YELLOW,
  //   },
  // });
  // addClickEvent(viewer)
  addEntityClickEvent(viewer)
  // addEntity()
  // add3DTiles()
  // addWater()
  // addRadar()
  // 当相机移动时就会调用此函数
  // viewer.camera.changed.addEventListener(() => {
  //   console.log(3333);
  // })
});
</script>

<template>
  <div id="cesiumContainer">
    <button class="toggle-button" @click="isToggle = !isToggle">
      打开功能列表
    </button>
    <legend-control></legend-control>
  </div>
  <toggle-control v-if="isToggle"></toggle-control>
</template>

<style lang="scss">
#cesiumContainer {
  width: 100vw;
  height: 100vh;
  position: relative;

  .cesium-viewer-bottom {
    visibility: hidden;
  }

  .toggle-button {
    position: absolute;
    top: 100px;
    left: 50px;
    cursor: pointer;
    z-index: 1000;
  }
}
</style>
